<script setup>
import { unsafeWindow } from '$';
import APlayer from "APlayer"; // 引入音乐插件
import "APlayer/dist/APlayer.min.css"; // 引入音乐插件的样式
import { ref, watch } from 'vue';
const showPlayer = ref(false)
const musicList = ref([])
watch(musicList, (nVal, oVal) => {
  if (mAp) {
    addClearBtn()
  }
  window.localStorage.setItem('monkeyMusicList', JSON.stringify(nVal))
}, { deep: true })
const storage = window.localStorage.getItem('monkeyMusicList')
const mkPlayerInstance = window.localStorage.getItem('mkPlayerInstance')
musicList.value = storage ? JSON.parse(storage) : []
const channel = new BroadcastChannel('monkeyPlayer')
let mAp = null

const createPlayer = () => {
  showPlayer.value = true
  nextTick(() => {
    mAp = new APlayer({
      container: document.getElementById('monkey-player'),
      fixed: true,
      loop: 'all',
      order: 'list',
      preload: 'auto',
      audio: musicList.value
    })
    mAp.setMode('normal')
    mAp.on('error', (error) => {
      mAp.list.remove(mAp.list.index)
      window.localStorage.setItem('monkeyMusicList', JSON.stringify(mAp.list.audios))
    })

    window.localStorage.setItem('mkPlayerInstance', new Date().getTime())
    channel.onmessage = (event) => {
      if (event.data.action === 'add') {
        mAp.list.add(event.data.list)
        musicList.value.push(event.data.list)
      }
      if (event.data.action === 'play') {
        mApPlay(event.data.list)
      }
      if (event.data.action === 'checkIns') {
        channel.postMessage({ action: 'answerCheckIns' })
      }
    };
    addClearBtn()

    window.addEventListener('beforeunload', function (event) {
      event.returnValue = ''; // Chrome需要设置returnValue属性
      if (mAp) {
        window.localStorage.removeItem('mkPlayerInstance')
      }
    })
  })
}

const addClearBtn = () => {
  let liDoms = document.querySelectorAll('.aplayer-list li')
  for (let i = 0; i < liDoms.length; i++) {
    if (!liDoms[i].classList.contains('has-clear')) {
      let clearBtn = document.createElement('span')
      clearBtn.innerText = 'X'
      clearBtn.classList.add('aplayer-list-clear')
      liDoms[i].appendChild(clearBtn)
      liDoms[i].classList.add('has-clear')
    }
  }
  let clearBtns = document.querySelectorAll('.aplayer-list .aplayer-list-clear')
  for (let i = 0; i < clearBtns.length; i++) {
    clearBtns[i].onclick = (e) => {
      let removeIndex = e.target.parentElement.children[1].innerText - 1
      mAp.list.remove(removeIndex)
      console.log(mAp.list);
      window.localStorage.setItem('monkeyMusicList', JSON.stringify(mAp.list.audios))
      e.stopPropagation()
    }
  }
}

const mApAdd = (addItem) => {
  if (!(musicList.value.find(info => info.title === addItem.title && info.author === addItem.author))) {
    musicList.value.push(addItem)
    if (mAp) {
      mAp.list.add(addItem)
    } else {
      toast('已加入播放列表')
      channel.postMessage({ action: 'add', list: addItem })
    }
  }
}

const mApPlay = (playItem) => {
  if (mAp) {
    const index = mAp.list.audios.findIndex(item => item.title === playItem.title && item.url === playItem.url)
    mAp.list.switch(index)
    if (mAp.audio.paused) {
      mAp.play()
    }
  } else {
    channel.postMessage({ action: 'play', list: playItem })
  }
}

const toast = (msg) => {
  let toast = document.createElement('div')
  toast.classList.add('monkey-toast')
  toast.innerText = msg
  toast.setAttribute('style', 'padding: 8px 12px; width: fit-content;background: rgba(0, 0, 0, 0.7);border-radius: 8px;color: #fff;position: fixed;top: 20%;left: 50%;transform: translate(-50%, -50%);z-index: 3000;')
  document.body.appendChild(toast)
  setTimeout(() => {
    document.body.removeChild(toast)
  }, 3000)
}

onMounted(() => {
  let aTags = document.querySelectorAll('a')
  for (let i = 0; i < aTags.length; i++) {
    aTags[i].setAttribute('target', '_blank')
  }

  if (window.location.pathname === '/') {
    if (!mkPlayerInstance) {
      createPlayer()
    } else {
      let fixTimer = setTimeout(() => {
        window.localStorage.removeItem('mkPlayerInstance')
        createPlayer()
      }, 1500)
      channel.onmessage = (event) => {
        if (event.data.action === 'answerCheckIns') {
          if (fixTimer) {
            clearTimeout(fixTimer)
          }
        }
      }
      channel.postMessage({ action: 'checkIns' })
    }
  } else {
    const ap4 = unsafeWindow.ap4
    if (ap4) {
      mApAdd(ap4.music)
      ap4.on('play', () => {
        ap4.pause()
        mApPlay(ap4.music)
      })
    } else {
      console.log('未发现ap4');
    }
  }
})

</script>

<template>
  <div class="hifi-player" v-show="showPlayer">
    <div class="audio-module">
      <div class="module-bg"></div>
      <div class="module-con">
        <div class="monkey-player-container">
          <div id="monkey-player"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.hifi-player {
  margin-bottom: 66px;
}

.audio-module {
  position: fixed;
  width: 100%;
  height: 66px;
  bottom: 0;
  z-index: 1000;
  background: #333;
}

.module-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 66px;
  background-color: #000;
  -webkit-filter: blur(90px);
  -moz-filter: blur(90px);
  -ms-filter: blur(90px);
  filter: blur(90px);
  box-shadow: 0 -10px 20px #403f3f;
}

.module-con {
  width: 100%;
  height: 66px;
  padding-right: 15px;
  margin-right: auto;
  margin-left: auto;
  display: flex;
}

.monkey-player-container {
  /* flex: 0 0 75%; */
  flex: 1;
  will-change: transform;
  padding-right: 15px;
}

.monkey-player-container #monkey-player.aplayer {
  max-width: 100% !important;
}

.monkey-player-container :deep(.aplayer.aplayer-fixed) .aplayer-body {
  max-width: 100% !important;
}

:deep(.aplayer-list-author) {
  margin-right: 10px;
}

:deep(.aplayer-list-clear) {
  width: 18px;
  text-align: center;
  position: absolute;
  top: 0;
  right: 0;
}

@media (max-width: 576px) {
  .module-con {
    padding-right: 0;
  }
}

@media (min-width: 576px) {
  .module-con {
    max-width: 540px;
  }
}

@media (min-width: 768px) {
  .module-con {
    max-width: 720px;
  }
}

@media (min-width: 992px) {
  .module-con {
    max-width: 960px;
  }
}

@media (min-width: 1200px) {
  .module-con {
    max-width: 1030px;
  }
}

:deep(.monkey-toast) {
  width: 100px;
  height: 100px;
  background: #000;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 3000;
}
</style>
